package cn.tedu.v1.v1;

import java.io.*;
import java.net.*;

/**
 * 聊天室  Version 1.1
 * 服务器  功能：1：服务器申请端口号：软件具备端口号
 *             2.在start方法中，等待客户端链接，返回socket
 *               IO读入
 *        【新增】3.所有服务端异常，全部捕获，明确提示
 *              4.关闭serverSocket
 */
public class Server {
    private ServerSocket serverSocket;//  -

    public Server() {   //+
        try {
            serverSocket = new ServerSocket(6666);
            //BindException    端口号已经被占用
        } catch (BindException e) {
            System.out.println("请检查端口号，被占用了~");
        } catch (IOException e) {
            System.out.println("请检查端口号，被占用~");
        }
    }

    public void start() {

        BufferedReader br = null;
        Socket socket = null;
        try {
            System.out.println("等待客户端连接");
            socket = serverSocket.accept();//卡住--客户端有连接--通过
            System.out.println("一个客户端连接上了");

            InputStream is = null;
            //OutputStream  os=new OutputStream() ;
            //OutputStreamWriter osw=new OutputStreamWriter(os);
            //BufferedWriter bw=new BufferedWriter(osw);
            //PrintWriter pw=new PrintWriter(bw);
            InputStreamReader isr = null;


            is = socket.getInputStream();//低级流---读入
            isr = new InputStreamReader(is, "UTF8");
            br = new BufferedReader(isr);

            while (true) {
                String str = null;//获取一行字符串，交给str保存
                str = br.readLine();
                System.out.println("客户端：" + str);//打印  客户端发过来文本
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("请检查客户端/服务器端编码集：不一致~");
        } catch (SocketException e) {
            System.out.println("客户端链接被重置了~");
        } catch (IOException e) {
            System.out.println("客户端链接失效了~");
        } finally {
            //关闭流   关闭socket
            if (br != null) {
                try {
                    br.close();
                    socket.close();
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("客户端socket断开连接~");
                }


            }
        }
    }

    public static void main(String[] args) {
        Server server=new Server();
        server.start();
    }
}
